import {
  getAdminDictionaryPageList,
  deleteAdminDictionary
} from '@/services/adminDictionaryService';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';
import { dateFormat, timeFormat } from '@/utils/common';

/**
 *
 * @constructor
 */
const AdminDictionaryPage: React.FC<unknown> = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [updateData, setUpdateData] = useState<AdminDictionaryType.AdminDictionaryRequest>(
    {} as AdminDictionaryType.AdminDictionaryRequest,
  );
  const actionRef = useRef<ActionType>();

  /**
   *
   * @param
   */
  const doDelete = async (model: AdminDictionaryType.AdminDictionaryResponse) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteAdminDictionary({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  /**
   *
   */
  const columns: ProColumns<AdminDictionaryType.AdminDictionaryResponse>[] = [

    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true,
    },

    {
      title: '字典名称',
      dataIndex: 'Name'
    },

    {
      title: '字典值',
      dataIndex: 'Value'
    },

    {
      title: '字典标识',
      dataIndex: 'Remark',
      hideInSearch: true,
    },

    {
      title: '父级',
      dataIndex: 'ParentId',
      hideInSearch: true,
      render(dom, entity) {
        return entity.Parent?.Value;
      }
    },

    {
      title: '新增时间',
      dataIndex: 'AddTime',
      hideInSearch: true,
      render(dom, entity) {
        return dateFormat(entity.UpdateTime, 'yyyy-mm-dd hh:mm:ss')
      }
    },

    {
      title: '修改时间',
      dataIndex: 'UpdateTime',
      hideInSearch: true,
      render(dom, entity) {
        return dateFormat(entity.UpdateTime, 'yyyy-mm-dd hh:mm:ss')
      }
    },

    {
      title: '新增人',
      dataIndex: 'AddUserId',
      hideInSearch: true,
      render(dom, entity) {
        return <span>{entity.AddUser?.UserName ?? ''}</span>
      },
    },

    {
      title: '修改人',
      dataIndex: 'UpdateUserId',
      hideInSearch: true,
      render(dom, entity) {
        return <span>{entity.AddUser?.UserName ?? ''}</span>
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: AdminDictionaryType.AdminDictionaryResponse) => (
        <Space split={<Divider type="vertical" />}>
          <Typography.Link
            onClick={() => {
              record.ParentId = record.ParentId === 0 ? undefined : record.ParentId;
              setUpdateData(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<AdminDictionaryType.AdminDictionaryResponse>
        headerTitle="字典管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => { setCreateModalVisible(true) }}
          >
            新建
          </Button>,
        ]}
        request={async (params: any, sorter: any) => {
          const searchParams: PageInfo.PageRequest = {
            ...params,
          };
          // eslint-disable-next-line guard-for-in
          for (const key in sorter) {
            searchParams.sortField = key;
            searchParams.sortOrder = sorter[key] as any;
          }
          searchParams['@relationships'] = "ParentInfo,UserInfo";
          const { Items, StatusCode } = await getAdminDictionaryPageList(searchParams);
          return {
            data: Items[0]?.Records || [],
            success: StatusCode === 200,
            total: Items[0].Total,
          } as any;
        }}
        columns={columns}
      />
      {createModalVisible ? <CreateModal
        modalVisible={createModalVisible}
        onSubmit={() => { setCreateModalVisible(false); actionRef.current?.reload(); }}
        onCancel={() => { setCreateModalVisible(false); actionRef.current?.reload(); }}
      /> : null}
      {updateModalVisible ? <UpdateModal
        dictionary={updateData}
        modalVisible={updateModalVisible}
        onSubmit={() => { setUpdateModalVisible(false); actionRef.current?.reload(); }}
        onCancel={() => { setUpdateModalVisible(false); actionRef.current?.reload(); }}
      /> : null}
    </PageContainer>
  );
};

export default AdminDictionaryPage;
